/*
 * @Author: your name
 * @Date: 2020-06-02 11:01:10
 * @LastEditTime: 2020-06-02 11:14:47
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \tuyibo\servers\api\upAvatar.js
 */ 

var express = require('express');
var up_router = express.Router();
var path = require('path')
var fs = require('fs')

const crypto = require('crypto')
//上传图片的模板
var multer = require('multer');
//生成的图片放入uploads文件夹下
var uploadOpts = {"dest":path.join(process.cwd(), 'static//images/Avatar')}
var uploadMulter = multer(Object.assign(uploadOpts,{'limits': { fileSize: 1024 * 1024 * 2, files:1 }})).single('file')

// 上传图片
up_router.post('/uploadlink', async (req, res) => {
	let result = {
		'code': 500
	}
  uploadMulter(req, res, function (err) {
    if (err instanceof multer.MulterError) {
			result.msg = err.message
			return res.json(result)
    } else if (err) {
			result.msg = err.message
			return res.json(result)
    }
		let file = req.file
		//let {pos, dir } = req.body

		var filename = file.originalname;
		var extname = path.extname(filename);
		var refilename = crypto.createHash('md5').update(path.basename(filename, extname)).digest("hex")
		var allname = refilename + extname
		var newPath = file.destination + "/" + allname
		fs.renameSync(file.path, newPath); //重命名

		var fileobj = {
			title: `Avatar/${allname}`,
			original: filename,
			type: file.mimetype,
			size: file.size,
			ext: extname,
			code: 200,
		}

		var GORET = function (r) {
			if (req.query["_csrf"] == undefined) {
				return res.json(r)
			} else {
				return res.end(JSON.stringify(r))
			}
		}
		GORET(fileobj)
  })	

})

module.exports = up_router